import React, { Component } from 'react';
import { withRouter, Link, Switch, Route, HashRouter as Router } from 'react-router-dom'
import { Layout, Menu, Icon, Input, Dropdown } from 'antd';

import PersonalStyle from './personal/personalStyle'
import Topic from './specialMonitoring/topic'
import DataStatistics from './data/dataStatistics'
import AddTopic from './specialMonitoring/addTopic'
import TopicDetail from './specialMonitoring/topicDetail'
import Error403 from './403'
import Error404 from './404'
import Data from './data/data.jsx'//数据统计
import SystemBase1 from './systemSetup/system-base1.jsx'//系统设置
import AddItem from './addItem'
import ImportData from './importData'
import Index from './index/index' //首页

import 'antd/dist/antd.css';
import "./../static/basicStyle.styl";
import Focus from './tero/focus.jsx';
import Tero from './tero/tero.jsx';
import Sidebar from './tero/sidebar.jsx';
import Warn from './tero/warning_information.jsx'
import Sample from './tero/sample_library.jsx'
import DataStudy from './dataStudy/data_study.jsx'
import $ from 'jquery';
import u from '../common.js'
import Loading from './loading.js'
import SearchCont from './headSearch/searchCont.jsx'
import Journa from './tero/journalism.jsx';
import Weixinqun from './routineMonitoring/weixinqun.jsx'
// import keyPerson from './routineMonitoring/keyPerson.jsx'
import GzDetail from './routineMonitoring/component/gzDetail'
import { message } from 'antd';
import Guide from './guide.js'

const { Header, Sider, Content } = Layout;
const SubMenu = Menu.SubMenu;

// @withRouter
export default class BasicPage extends React.Component {
  state = {
    collapsed: false,
    list: [1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 11],
    flag: false,
    name: localStorage.getItem('name'),
    key: '1',
    inputValue: '',
    keyWordValue: '',
    keycheck:[sessionStorage.getItem("basickeyword") || '1'],
    subcheck:[sessionStorage.getItem("basickeysub") || ''],
    yujingflag:true,
    // valueflag:true
    guideFlage:true,
    display:'none',
    display2:'none'
  };
  goRouter(d) {
    this.props.history.push(d)
  };
  computed() {
    $('.persoalCenter_son_pop_bottom').css('height', $('.persoalCenter_son_pop').height() - 70 + 'px')
    $(window).resize(function () {
      $('.persoalCenter_son_pop').css('height', '89vh')
      $('.persoalCenter_son_pop_bottom').css('height', $('.persoalCenter_son_pop').height() - 70 + 'px')
    })
  }
  componentWillMount() {
    this.sinmplie()
    u.objserve(u.yujing,()=>{
      this.isallread()
    })
  }
  


  componentDidMount() {
    this.setState({
      keyWordValue: sessionStorage.getItem('inputVal')
    })
    this.computed();
    sessionStorage.setItem('loading', 'block')
  }
  goRouter(d) {
    this.props.history.push(d)
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }
  handle() {
    u.logout(data => {
      window.location.href = u.testurl + '/login'
    })
  }
  handleDetail(id,content) {
    localStorage.setItem('content',content);
    const w = window.open('about:blank');
    w.location.href = u.testurl + '/journa?' + id
  }

  isallread(){
    let [arr, brr] = [[], JSON.parse(localStorage.getItem('readIndex')) || []]
    this.state.list.forEach((el) => {
      arr.push(el.id)
    })
    if (brr.length < this.state.list.length) {
      return
    }
    let crr = [...brr, ...arr];
    let newArr = Array.from(new Set(crr));
    crr.length - newArr.length === this.state.list.length?this.setState((props,prevState)=>({
      yujingflag:false
    })):''
  }

  
  sinmplie() {
    let data = {
      "startTime": u.getDate(0, false),
      "endTime": u.getDate(0, true),
      "page": 1,
      "size": 40
    };
    u.simplee(data, data => { //预警
      // if (data && data.data) {
      if (data.data.length > 0) {
        let keyWord = data.data.data[0].keyWord
        // localStorage.setItem('shouYeKeyWord',keyWord)
      }
      if (u.isArray(data.data)) {
        this.setState((prevState, props) => ({
          list: data.data
        }),()=>{
          this.isallread()
        })
      } else {
        this.setState((prevState, props) => ({
          list: data.data.data
        }),()=>{
          this.isallread()
        })
      }
     

    })

  }
  setKey(key, keysub) {
    sessionStorage.setItem('inputVal', '')
    sessionStorage.setItem('basickeyword',key)
    let url = window.location.hash
    this.setState({
      keyWordValue: '',
      keycheck:[key],
      subcheck:!(url.includes('weixinqun') || url.includes('sample')|| url.includes('warn'))?['']:['sub1']
      
    })
    keysub ? sessionStorage.setItem('basickeysub', keysub) : sessionStorage.setItem('basickeysub', '')
  }
  onChangeWord(e) {
    let value = e.target.value
    if (e.target.value === '') {
      sessionStorage.setItem('inpval', '')
    }
    this.setState({
      keyWordValue: value
    })
  }
  //获取搜索框中的值
  getValue = () => {
    let inpval = $('#inp').val();
    console.log(inpval)
    if (!u.tirm(inpval)) {
      $('#inp').val('')
      message.error( '输入不能为空', [1], )
      return
    } else {
      inpval = u.tirm(inpval);
      console.log(inpval)
    }
    sessionStorage.setItem('inputVal', inpval);//存储input框中的值到本地
    window.location.hash = '/searchCont/1'
  }

  componentDidUpdate() {
    if(window.location.hash === '#/searchCont/1')return
    $('#inp').val('')
  }
  opensub(openKeys){
    this.setState((prevState,props)=>({
      subcheck:openKeys
    }))
    let url = window.location.hash
    if(url.includes('weixinqun') || url.includes('sample')|| url.includes('warn')){
      return
    }
    this.setState((prevState,props)=>({
      keycheck:['2']
    }))
    this.goRouter('/weixinqun/wechat');
    this.setKey('2', 'sub1');
    sessionStorage.setItem('keyword', '5')
    localStorage.setItem("cgkey",0)
    localStorage.setItem("weixinkey",0)
  }
  onGuideOpen(flag){
    this.setState({
      guideFlage:flag

    })
  }
  //功能简介图标 鼠标移入移出事件
  handleMouseEnter(){
    this.setState({
      display:'block'
    })
  }
  handleMouseEnter2(){
    this.setState({
      display2:'block'
    })
  }
  handleMouseLeave(){
    this.setState({
      display:'none'
    })
  }
  handleMouseLeave2(){
    this.setState({
      display2:'none'
    })
  }
  render() {
    let yjstyle = {display:'inline-block',height:'10px',width:'10px',backgroundColor:'#ff0f50',borderRadius:'50%',transform:this.state.yujingflag?"scale(1)":"scale(0)",position:"relative",left:'22px',top:"-10px"};
    const menu = (
      <Menu>
        {/* <Menu.Item> */}
          {/* <Link to="/personalStyle/accountInfo" onClick={() => { sessionStorage.setItem('personalkey', '1'); window.location.reload() }}>账户信息</Link> */}
        {/* </Menu.Item> */}
        {/* <Menu.Item> */}
          {/* <Link to="/personalStyle/personalInfo" onClick={() => { sessionStorage.setItem('personalkey', '2'); window.location.reload() }}>个人资料</Link> */}
        {/* </Menu.Item> */}
        <Menu.Item>
          <a href="#" onClick={() => {
            this.handle()
          }}>退出系统</a>
        </Menu.Item>
      </Menu>
    );
    return (

      <Layout id="basicContainer">
       <Guide guideFlage={this.state.guideFlage} onGuideOpen={this.onGuideOpen.bind(this)}/>
        <Loading />
        <Sider
          trigger={null}
          collapsible
          collapsed={this.state.collapsed}
        >
          <div className="logo">西藏开源信息情报平台</div>
          <Menu theme="dark" mode="inline"
            defaultSelectedKeys={[sessionStorage.getItem('basickeyword') || '1']}
            defaultOpenKeys={[sessionStorage.getItem('basickeysub')]}
            onOpenChange={this.opensub.bind(this)}
            selectedKeys={this.state.keycheck}
            openKeys={this.state.subcheck}
          >
            <Menu.Item key="1" onClick={() => {
              this.goRouter("/index")
              this.setKey('1')
            }
            }
            >
              <Icon type="home" />
              <span>首页</span>
            </Menu.Item>
            <SubMenu key="sub1"  title={<span><Icon type="search" /><span
              onClick={() => {
                this.setKey('2', 'sub1')
           
              }}
            >信息巡查</span></span>}>
              <Menu.Item key="2" className="basicDrop" onClick={() => {
                // this.goRouter('/tero/whole');
                if(window.location.hash.includes('weixinqun')){
                  return
                }
                this.goRouter('/weixinqun/wechat');
                this.setKey('2', 'sub1');
                sessionStorage.setItem('keyword', '5')
                localStorage.setItem("cgkey",0)
                localStorage.setItem("weixinkey",0)
              }}>常规检测</Menu.Item>
              {/* <Menu.Item key="3" className="basicDrop" onClick={() => {
                this.goRouter('/inspect/navfocus')
                this.setKey('3', 'sub1')
              }}>重点人/组织检测</Menu.Item> */}
              <Menu.Item key="4" className="basicDrop"
                onClick={() => {
                  this.goRouter("/sample")
                  this.setKey('4', 'sub1')

                }}>预警信息</Menu.Item>
              <Menu.Item key="5" className="basicDrop" onClick={() => {
                this.goRouter('/warn')
                this.setKey('5', 'sub1')
              }}>样本库</Menu.Item>
            </SubMenu>
            <Menu.Item key="6"
              onClick={() => {
                this.goRouter("/dataStudy")
                this.setKey('6')
              }}
            >
              <Icon type="book" />
              <span >信息研判</span>
            </Menu.Item>
            <Menu.Item key="7" onClick={() => {
              this.goRouter("/dataStatistics")
              // this.goRouter("/data")
              this.setKey('7')
            }}>
              <Icon type="profile" />
              <span>数据统计</span>
            </Menu.Item>
            <Menu.Item key="8" onClick={() => {
              this.goRouter("/topic")
              this.setKey('8')
            }}>
              <Icon type="line-chart" />
              <span>专题监测</span>
            </Menu.Item>
            <Menu.Item key="9" onClick={() => {
              this.goRouter("/systemBase/systemKeywords")
              this.setKey('9')
              sessionStorage.setItem('systemkeyword', '1')
            }}>
              <Icon type="setting" />
              <span>系统设置</span>
            </Menu.Item>
          </Menu>
        </Sider>
        <Layout>
          <Header className="basicHeader">
            <div className="basicSearch">
              <Input placeholder="请输入搜索内容..." id='inp' 
              // value={this.state.keyWordValue}
              // onChange={this.onChangeWord.bind(this)}
              onKeyDown={(e)=>{
                if(e.keyCode!==13)return
                this.getValue()}}/>
              <img src={require("./../static/image/search_icon.png")} alt=""
                onClick={this.getValue} />
            </div>
            <div className="persoalCenter">
              <img className='guideIntro' src={require('./../static/image/guideOpen.png')}  onClick={this.onGuideOpen.bind(this,true)} onMouseEnter={this.handleMouseEnter.bind(this)} onMouseLeave={this.handleMouseLeave.bind(this)}/>
              <span className='guideTip' style={{display:this.state.display}}>功能简介</span>
              {/* <img src={require("./../static/image/screen.png")} alt="" style={{ marginRight: 28 }} /> */}
              <div className='persoalCenter_son' >
              <span style={yjstyle}></span>
                <img src={require("./../static/image/notification.png")} onClick={() => {
                  this.setState({
                    flag: !this.state.flag
                  })
                }} alt="" align='top' onMouseEnter={this.handleMouseEnter2.bind(this)} onMouseLeave={this.handleMouseLeave2.bind(this)} />
                <span className='newsTip' style={{display:this.state.display2}}>预警消息</span>
                <div className={this.state.flag ? 'persoalCenter_son_pop persoalCenter_son_pop_active' : 'persoalCenter_son_pop'}>
                  <img src={require('./../static/image/X_nor.png')} alt="" onClick={() => {
                    this.setState({
                      flag: false
                    })
                  }} />
                  <div className='persoalCenter_son_pop_top'>
                    <span>预警消息</span>
                    <span style={{ cursor: 'pointer' }} onClick={() => {
                      this.setKey('4', 'sub1')
                      this.goRouter('/sample')
                      this.setState((prevState, props) => ({
                        flag: false,
                      }))
                      window.location.reload()

                    }}>进入消息中心</span>
                  </div>
                  <div className='persoalCenter_son_pop_bottom'>
                    <ul>
                      {
                        this.state.list.map((item, index) => {
                          return (<li key={index} onClick={() => {
                            this.handleDetail(item.id,item.content)
                          }}>
                            <div className='persoalCenter_li_top'>
                              <p dangerouslySetInnerHTML={{ __html: item.title }}></p>
                            </div>
                            <div className='persoalCenter_li_bottom'>
                              <p>{u.unixTime(item.addTime)}</p>
                            </div>
                          </li>)
                        })
                      }

                    </ul>
                  </div>
                </div>
              </div>
              <Dropdown overlay={menu}>
                <a className="ant-dropdown-link" href="javascript:void(0);" style={{ margin: '22px' }}>
                  {this.state.name} <Icon type="down" />
                </a>
              </Dropdown>
              <img src={require("./../static/image/userLogo.png")} alt="" className="userImg" />
            </div>
          </Header>
          <Content style={{ margin: '20px', height: "100%", background: '#fff', position: "relative" }} ref="myInput">
            <Switch>
              <Route path='/inspect' component={Focus} />
              <Route path='/personalStyle' component={PersonalStyle} />
              <Route path='/tero' component={Tero} />
              <Route path='/dataStatistics' component={DataStatistics} />
              <Route path='/topic' component={Topic} />
              <Route path='/addTopic' component={AddTopic} />
              <Route path='/topicDetail' component={TopicDetail} />
              <Route path='/data' component={Data} />
              <Route path='/systemBase' component={SystemBase1} />
              <Route path='/error403' component={Error403} />
              <Route path='/error404' component={Error404} />
              <Route path='/addItem' component={AddItem} />
              <Route path='/importData' component={ImportData} />
              <Route path='/index' component={Index} />
              <Route path='/Warn' component={Warn} />
              <Route path='/sample' component={Sample} />
              <Route path='/dataStudy' component={DataStudy} />
              <Route path='/map' component={DataStudy} />
              <Route path='/sidebar' component={Sidebar} />
              <Route path='/searchCont/:id' component={SearchCont} />
              <Route path='/journa' component={Journa} />
              <Route path='/weixinqun' component={Weixinqun} />
              <Route path='/gzDetail' component={GzDetail} />
              {/* <Route path='/keyPerson' component={keyPerson} /> */}
            </Switch>
          </Content>
        </Layout>
      </Layout>
    );
  }
}
